package org.example;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.Set;

public class EssentialDemo {
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        try (Jedis jedis = jedisPool.getResource()){
            jedis.flushAll();
            // 在此处调用测试代码
            //testGetAndSet(jedis);
            //testExistsAndDel(jedis);
            //testKeys(jedis);
            //testExpireAndTtl(jedis);
            //testType(jedis);
        }
    }
    public static void testGetAndSet(Jedis jedis) {
        System.out.println("测试 get 和 set");
        jedis.set("k1","111");
        jedis.set("k2","222");
        String result = jedis.get("k1");
        System.out.println("k1：" + result);
        result = jedis.get("k2");
        System.out.println("k2：" + result);
        result = jedis.get("k3");
        System.out.println("k3：" + result);
    }
    public static void testExistsAndDel(Jedis jedis) {
        System.out.println("测试 exists 和 del");
        jedis.set("k1","111");
        jedis.set("k2","222");
        jedis.set("k3","333");
        boolean ret = jedis.exists("k1");
        System.out.println("k1 : " + ret);
        long n = jedis.del("k1");
        ret = jedis.exists("k1");
        System.out.println("n : " + n);
        System.out.println("k1 : " + ret);
        n = jedis.del("k2","k3");
        System.out.println("n : " + n);
        ret = jedis.exists("k2");
        System.out.println("k2 : " + ret);
        ret = jedis.exists("k3");
        System.out.println("k3 : " + ret);
    }
    public static void testKeys(Jedis jedis) {
        System.out.println("测试 keys");
        jedis.set("k1","11");
        jedis.set("k2","22");
        jedis.set("k3","33");
        Set<String> arrayList = jedis.keys("*");
        System.out.println("* : " + arrayList);
    }
    public static void testExpireAndTtl(Jedis jedis)  {
        System.out.println("测试 expire 和 ttl");
        jedis.setex("key",2,"value");
        long ttl = 1;
        while (ttl > 0) {
            try {
                Thread.sleep(100);
                ttl = jedis.ttl("key");
                System.out.println("剩余：" + ttl);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public static void testType(Jedis jedis) {
        jedis.set("key1", "value");
        System.out.println(jedis.type("key1"));
        jedis.lpush("key2", "a", "b", "c");
        System.out.println(jedis.type("key2"));
        jedis.hset("key3", "name", "zhangsan");
        System.out.println(jedis.type("key3"));
        jedis.sadd("key4", "111", "222", "333");
        System.out.println(jedis.type("key4"));
        jedis.zadd("key5", 1, "aaa");
        System.out.println(jedis.type("key5"));
    }
}
